﻿/******************************************************************************
 * Copyright (C) 2015  671643387@qq.com
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 *****************************************************************************/

#include "RealmList.h"
#include <NodeCpp/AutoPtr.h>
#include "Shared/Log/Log.h"
#include "GlobalVars.h"
using NodeCpp::AutoPtr;

class RealmListHandler
{
public:
    void HandleRealmListFetchCallback(QueryResult* _Result, int)
    {
        if (_Result) {
            sRealmList.HandleFetchRealmList(_Result);
            SAFE_DEL(_Result);
        }
    }
} G_RealmListHandler_;

RealmList::RealmList(void)
	: UpdateInterval_(5000)
    , UpdateTimeElasped_(0)
    , Realms_()
{

}

RealmList::~RealmList(void)
{
	Clear();
}

void RealmList::Update(time_t _Diff)
{
    UpdateTimeElasped_ += _Diff;
    if (UpdateTimeElasped_ < UpdateInterval_) {
        return;
    }
    UpdateTimeElasped_ = 0;

    sLoginDB.AsyncQuery(&G_RealmListHandler_,
        &RealmListHandler::HandleRealmListFetchCallback,
        0, "SELECT * FROM realmlist;");
}

void RealmList::HandleFetchRealmList(QueryResult* _Result)
{
    Realms_.clear();
    if (_Result)
    {
        do
        {
            struct Realm _Realm = { 0 };
            _Realm.Id = (*_Result)[0].AsUInt32();
            _Realm.Name = (*_Result)[1].AsString();
            _Realm.Address.append((*_Result)[2].c_str())
                .append(":").append((*_Result)[3].c_str());
            _Realm.Icon = (*_Result)[4].AsUInt8();
            _Realm.Flags = (RealmFlags)(*_Result)[5].AsUInt8();
            _Realm.Timezone = (*_Result)[6].AsUInt8();
            _Realm.PopulationLevel = (*_Result)[8].AsFloat();
            Realms_.push_back(_Realm);
        } while (_Result->NextRow());
    }

    sLog.outDebug("*** Loaded %d realms", Realms_.size());
}
